package com.gf.pokemon.platform.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.PatternMatchUtils;

import com.gf.pokemon.constants.PokeConstants;
import com.gf.pokemon.dto.LoginUser;
import com.gf.pokemon.platform.utils.LoginUserHelper;

public class LoginCheckFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = -810687002225616279L;

	private static final Logger logger = Logger.getLogger(LoginCheckFilter.class);
	
	private List<String> excludePath;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String excludePathv = filterConfig.getInitParameter("excludePath");

		excludePath = new ArrayList<String>();
		if (StringUtils.isNotBlank(excludePathv)){
			String[] paths = excludePathv.split(";");
			excludePath.addAll(Arrays.asList(paths));
		}
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest) request;
		HttpServletResponse hresponse = (HttpServletResponse) response;
		String path = hrequest.getPathInfo();
		//非登录功能放过
		if(urlPathMatch(excludePath, path)) {
			filterChain.doFilter(hrequest, hresponse);
			return;
		}
		
		if(hrequest.getSession().getAttribute(
				PokeConstants.SESSION_USER)==null){
			logger.info(path+" need login.");
			if(isAjaxRequest(hrequest)){
				hresponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			}else{
				hresponse.sendRedirect("/admin/show");
			}
			return;
		}else{
			LoginUser loginUser = (LoginUser) hrequest.getSession().getAttribute(
					PokeConstants.SESSION_USER);
			LoginUserHelper.setLoginUser(loginUser);
			try{
				filterChain.doFilter(hrequest, hresponse);
			}finally{
				LoginUserHelper.removeLoginUser();
			}
		}
		
	}

	private boolean urlPathMatch(List<String> ePaths, String path) {
		for(String epath:ePaths){
			if(PatternMatchUtils.simpleMatch(epath, path)){
				return true;
			}
		}
		return false;
	}
	
	private boolean isAjaxRequest(HttpServletRequest request){
		 return request.getHeader("X-Requested-With")==null?false:true; 
	}
	
	public static void main(String[] args){
		String pattern = "/**/*.js";
		System.out.println(PatternMatchUtils.simpleMatch(pattern, "/js/a"));
	}

}
